package com.dodock.android.banglapapers.ui;

import java.util.HashMap;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.Settings.Secure;
import android.view.Display;
import android.view.Window;
import android.view.WindowManager;

import com.dodock.android.banglapapers.BanglaNews;
import com.dodock.android.banglapapers.Configuration;
import com.dodock.android.banglapapers.InternetConnectivity;
import com.dodock.android.banglapapers.MyApplication;
import com.dodock.android.banglapapers.NewsDetails;
import com.dodock.android.banglapapers.R;
import com.dodock.android.banglapapers.WebServerOperation;
import com.dodock.android.banglapapers.db.DatabaseManager;
import com.dodock.android.banglapapers.imageLoader.FileCache;
import com.google.analytics.tracking.android.GAServiceManager;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;
import com.urbanairship.UAirship;
import com.urbanairship.push.PushManager;


public class SplashActivity extends Activity {

	private static final int STOPSPLASH = 0;
	private static final long SPLASHTIME = 2500;
	DatabaseManager db;	
	private WindowManager wm;
	private Display ds;	
	
	private Tracker mGaTracker;
	private GoogleAnalytics mGaInstance;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
				
		//Google Analytics
		try{
			GAServiceManager.getInstance().setDispatchPeriod(0);
		    mGaInstance = GoogleAnalytics.getInstance(this);
		    mGaTracker = mGaInstance.getTracker(getResources().getString(R.string.ga_trackingId));
		    
		}
		catch (Exception e) {
		}
		//--Google Analytics
		
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.splash);
		String filePath = getFilesDir().getAbsolutePath();
		BanglaNews.setFilePath(filePath);
		db = new DatabaseManager(this);
		db.initializeDatabase();
		BanglaNews.setDatabaseManager(db);
		getWindowSize();
		
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
		if (prefs.getBoolean("time_saved", false) == false) {								
			editor.putLong("time",System.currentTimeMillis());
			editor.putBoolean("time_saved", true);
			editor.commit();
		}else{
			Long previousTime = prefs.getLong("time", 0);
			Long currentTime = System.currentTimeMillis();
			if(currentTime - previousTime > 86400000){				
				editor.putLong("time",System.currentTimeMillis());		
				editor.commit();
				try{
					FileCache.clear();
					if(BanglaNews.hashtable != null){
						BanglaNews.hashtable.clear();
					}
					else{
						BanglaNews.hashtable = new HashMap<String, NewsDetails>();
					}
				}
				catch (Exception e) {
					
				}
				
			}
		}
		if(BanglaNews.hashtable == null){
			BanglaNews.hashtable = new HashMap<String, NewsDetails>();
		}
	}
	
	private void  getWindowSize() {
		wm = (WindowManager) getSystemService(WINDOW_SERVICE);
		ds = wm.getDefaultDisplay();
		BanglaNews.SCREEN_WIDTH = ds.getWidth();
		BanglaNews.SCREEN_HEIGHT = ds.getHeight();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		com.facebook.Settings.publishInstallAsync(this, MyApplication.fb_app_id);
		if(InternetConnectivity.isConnectedToInternet(getApplicationContext())){
			if ( BanglaNews.configuration == null) {
				GetConfiguration gcit = new GetConfiguration();
				gcit.execute();
			}else{
				startSplashHandler();
			}
		}else{
			openInternetSettingsScreen();
		}
	}

	
	
	
	private void startSplashHandler() {
		// TODO Auto-generated method stub
		String filePath = getFilesDir().getAbsolutePath();
		BanglaNews.setFilePath(filePath);
		Message msg = new Message();
		msg.what = STOPSPLASH;
		splashHandler.sendMessageDelayed(msg, SPLASHTIME);
	}


	private class GetConfiguration extends AsyncTask<Void, Void, Void> {
		@Override
		protected Void doInBackground(Void... params) {
			getConfigurationJson();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			startSplashHandler();
		}
	}
	
	private void getConfigurationJson() {
		// TODO Auto-generated method stub
		String urlPath = BanglaNews.BASE_URL + "DDNGetConfig" + "?appVersion="+MyApplication.app_version;
		try {
			String serverResonse = WebServerOperation.HTTPrequest(urlPath);
			parseConfigurationJSON(serverResonse);
		} catch (Exception e) {
		}
	}
	
	private void parseConfigurationJSON(String serverResonse) throws Exception {
		// TODO Auto-generated method stub
		Configuration configuration = new Configuration();
		JSONObject jObject = new JSONObject(serverResonse);
		String helpText = jObject.getString("helptext");
		configuration.setHelpText(helpText);
		String aboutText = jObject.getString("abouttext");
		configuration.setAboutText(aboutText);
		String sendToFriendText = jObject.getString("sendtofriendtext");
		configuration.setSendToFriendText(sendToFriendText);
		BanglaNews.configuration = configuration;
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		try {
			mGaTracker.sendView("/Splash");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	protected void onStop() {
		super.onStop();
	}

	private Handler splashHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case STOPSPLASH:
				startActivity(new Intent(SplashActivity.this, HomeActivity.class));
				finish();
				break;
			}
			super.handleMessage(msg);
		}
	};

	private void openInternetSettingsScreen()
	{
		final AlertDialog.Builder alert = new AlertDialog.Builder(SplashActivity.this);
		alert.setTitle("Connection failed");
		alert.setMessage("This application requires network access. Enable mobile network or Wi-Fi to download data");
		alert.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				Intent intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
				startActivity(intent);
			}
		});
		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				SplashActivity.this.finish();
			}
		});
		alert.show();
	}
}